package redis.inaction.clients.ops;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.IntStream;

@Slf4j
abstract class AbstractOps {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * hset, hgetall, hget
     */
    protected void redisOps(Consumer<Integer> hset,
                            Function<String, Map<String, String>> hgetAll,
                            BiFunction<String, String, String> hget,
                            String hashKey) {
        IntStream.range(1, 11).forEach(hset::accept);

        /*for(int i = 1; i < 11; i++){
            hset.accept(i);
        }*/

        Map<String, String> hgetAllValue = hgetAll.apply(hashKey);
        log.info("{}: {}", hashKey, writeValueAsString(hgetAllValue));
        String hgetVal = hget.apply(hashKey, "k_3");
        log.info("get from redis: {}, k_3 = {}", hashKey, hgetVal);
    }

    private String writeValueAsString(Object obj){
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("",e);
            return null;
        }
    }
}
